package HttpServlet;

import Entity.userinformation;

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.Optional;

@WebServlet(urlPatterns = {"/upload2"})
public class registerservlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(true);
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String phonenumber = request.getParameter("phonenumber");
        String email=request.getParameter("email");

        Jsonb jsonb = JsonbBuilder.create();
        userinformation MessageDTO = new userinformation(username,password,username,phonenumber,email);
        String str = jsonb.toJson(MessageDTO);
        FileInputStream fis = null;
        BufferedReader br = null;
        fis = new FileInputStream("src/main/LOGIN.txt");
        br = new BufferedReader(new InputStreamReader(fis));
        String line = null;
        while ((line = br.readLine()) != null) {
            userinformation personDTO = jsonb.fromJson(line, userinformation.class);
            if(personDTO.getUsername().equals(username))
            {
                request.setCharacterEncoding("UTF-8");
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().println("用户已存在！！请退回上一步继续操作");
                break;
            }
        }

        BufferedWriter out = null;
        try {
            out = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream("src/main/LOGIN.txt", true)));
            out.write(str+"\n");
        } catch (Exception e) {
            response.sendRedirect("/error.html");
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                response.sendRedirect("/error.html");
            }
        }
        request.setAttribute("msg","用户注册成功");
        response.sendRedirect("/index.html");
    }
}
